import sys

try:
    import encodeImage
except:
    pass

class FilterCondition(object):
    def isMatch(self, fn):
        return True

class Converter(object):
    def apply(self, fn, data):
        return data

class Filter(object):
    def __init__(self, cond, op):
        self.cond = cond 
        self.op = op

    def filter(self, fn, data):
        if self.cond.isMatch(fn):
            return self.op.apply(fn, data)
        return data

class FilterChain(object):
    def __init__(self, condOps):
        self.condOps = condOps

    def filter(self, fn, data):
        state = data
        for cond, op in self.condOps:
            if cond.isMatch(fn):
                state = op.apply(fn, data)
            if state is None:
                break
        return state

class StringExistsFilterCondition(FilterCondition):
    def __init__(self, pat):
        self.pat = pat

    def isMatch(self, fn):
        if fn.find(self.pat) != -1:
            return True
        return False

class EncryptionConverter(Converter):
    def __init__(self, key, iv):
        self.key = key
        self.iv = iv

    def apply(self, fn, data):
        return encodeImage.encode(self.key, self.iv, fn, data)

class FileDiscard(Converter):
    def apply(self, fn, data):
        print >>sys.stderr, 'Discarding',fn
        return None
